<template>
  <el-dialog
    :visible.sync="visible"
    append-to-body
    :before-close="beforeClose"
    width="900px"
    top="30px"
  >
    <div v-loading="loading">
      <div v-if="isSend" class="mb-1">
        <div class="text-sm text-warning">客户签约中请勿合同重做</div>
        <el-button @click="handleView">查看合同</el-button>

        <el-button @click="handleCopy(customerUrl)" class="mr-2">
          <i class="fa fa-link"></i>
          复制链接
        </el-button>
        <el-popover placement="top-start" title="客户签约地址" trigger="hover">
          <div>
            <qr-code :value="customerUrl" :size="140"></qr-code>
          </div>
          <el-button slot="reference">
            <i class="fa fa-qrcode"></i>
            扫描二维码
          </el-button>
        </el-popover>
        <el-button
          class="float-right"
          @click="getContract()"
          icon="el-icon-refresh"
          :loading="loading"
        >
          刷新
        </el-button>
        <el-button class="float-right mr-2" @click="handleReContract" :loading="submitLoading">
          重做合同
        </el-button>
      </div>
      <table class="table table-bordered table-vertical-middle">
        <colgroup>
          <col width="18%" />
          <col width="32%" />
          <col width="18%" />
          <col width="32%" />
        </colgroup>
        <tr>
          <td class="td-label">贷款主体</td>
          <td>{{ related.customer_name }}</td>
          <td class="td-label">{{ isCompany ? '社会统一信用代码' : '身份证号码' }}</td>
          <td>{{ isCompany ? related.register_no : related.lender_idcard }}</td>
        </tr>
        <tr>
          <td class="td-label">地址/通讯地址</td>
          <td :class="tdClass">
            <span v-if="isView">{{ contract.entrust_entity_address || '' }}</span>
            <el-input
              v-else
              v-model="editData.entrust_entity_address"
              placeholder="请输入客户地址"
            ></el-input>
          </td>
          <td class="td-label">联系电话</td>
          <td>
            {{ related.corp_phone }}
          </td>
        </tr>
        <tr>
          <td class="td-label">银行名称</td>
          <td>{{ related.claim_bank_name }}</td>
          <td class="td-label">放款金额(万元)</td>
          <td>{{ related.warranty_amount }}（{{ warrantyAmountCapital }}）</td>
        </tr>
        <tr>
          <td class="td-label">借款合同名称</td>
          <td :class="tdClass">
            <span v-if="isView">{{ contract.loan_contract_name || '' }}</span>
            <el-input
              v-else
              v-model="editData.loan_contract_name"
              placeholder="借款合同名称"
            ></el-input>
          </td>
          <td class="td-label">借款合同编号</td>
          <td :class="tdClass">
            <span v-if="isView">{{ contract.loan_contract_no || '' }}</span>
            <el-input
              v-else
              v-model="editData.loan_contract_no"
              placeholder="借款合同编号"
            ></el-input>
          </td>
        </tr>
        <tr>
          <td class="td-label">限率代偿担保合作协议编号</td>
          <td :class="tdClass">
            <span v-if="isView">{{ contract.join_no || '' }}</span>
            <el-input
              v-else
              v-model="editData.join_no"
              placeholder="限率代偿担保合作协议编号"
            ></el-input>
          </td>
          <td class="td-label">违约金标准：代偿金额百分比</td>
          <td :class="tdClass">
            <span v-if="isView">{{ contract.falsify_funds_rate || '' }}</span>
            <el-input
              v-else
              v-model="editData.falsify_funds_rate"
              v-input-number="{ min: 0, max: 100 }"
              placeholder="代偿金额百分比"
            >
              <span slot="append">%</span>
            </el-input>
          </td>
        </tr>
      </table>
      <div class="text-center py-4" v-if="!isView">
        <el-button type="primary" class="btn-long" :loading="submitLoading" @click="submit">
          {{ hasContract ? '修改' : '提交' }}委托合同
        </el-button>
      </div>

      <el-dialog
        top="30px"
        width="900px"
        append-to-body
        :close-on-click-modal="false"
        :before-close="coloseContract"
        :visible.sync="entrustView"
      >
        <pdf-view :contractId="contractId" :view-mode="true"></pdf-view>
      </el-dialog>
    </div>
  </el-dialog>
</template>

<script>
import { nzhToMoney, copyText } from '@vimi/utils-tool'
import PdfView from '@/credit/views/county/unionProvince/components/PdfView'
import { mapGetters } from 'vuex'
export default {
  components: {
    PdfView,
  },
  props: {
    visible: Boolean,
    queryId: String,
    viewMode: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      loading: false,
      related: {},
      submitLoading: false,
      editData: {},
      contract: {},
      entrustView: false,
    }
  },
  watch: {
    visible: {
      handler: function () {
        if (this.visible) {
          this.getData()
          this.getContract()
        }
      },
      immediate: true,
    },
  },
  computed: {
    ...mapGetters(['user']),
    isView() {
      return this.viewMode || this.isSend
    },
    isCompany() {
      return +this.related.customer_type === 1
    },
    tdClass() {
      return this.isView ? '' : 'input-td'
    },
    warrantyAmountCapital() {
      return nzhToMoney(this.related.warranty_amount * 10000)
    },
    signStatus() {
      return this.contract?.sign_status ?? 0
    },
    hasContract() {
      return !!this.contract.entrust_contract_id
    },
    contractId() {
      return this.contract.doc_id
    },
    isSend() {
      return +this.contract.sign_status > 0
    },
    customerUrl() {
      return window.location.origin + '/credit-h5/#/'
    },
  },
  created() {},
  methods: {
    handleReContract() {
      if (!this.contract.entrust_contract_id) {
        return
      }
      this.$prompt('请输入重做原因', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: value => (!value ? '请输入重做原因' : true),
      }).then(({ value }) => {
        const data = {
          sign_no: this.contract.sign_no,
          doc_id: this.contract.doc_id,
          related_id: this.contract.entrust_contract_id,
          sign_no_type: 1,
          re_sign_type: 1,
          re_sign_des: value,
          re_sign_person: this.user.realName,
          re_sign_time: this.$utils.dateFormat(new Date()),
          customer_related_id: this.queryId,
        }
        this.submitLoading = true
        this.$api
          .addData('credit', 're_sign_record', data)
          .then(() => {
            this.getContract()
          })
          .catch(err => {
            this.$message.error(err?.data?.error_description || '提交失败，请重试！')
          })
          .finally(() => {
            this.submitLoading = false
          })
      })
    },
    handleCopy(value) {
      const success = copyText(value)
      if (success) {
        this.$message.success('已复制到粘贴板')
      } else {
        this.$message.error('已复制到粘贴失败')
      }
    },
    coloseContract() {
      this.entrustView = false
    },
    handleView() {
      this.entrustView = true
    },
    validator() {
      const enumValidator = {
        entrust_entity_address: '请输入客户通讯地址',
        loan_contract_name: '请输入借款合同名称',
        loan_contract_no: '请输入借款合同号',
        join_no: '请输入限率代偿担保合作协议编号',
        falsify_funds_rate: '请输入违约金标准：代偿金额百分比',
      }

      if (!Number.isFinite(+this.editData.falsify_funds_rate)) {
        this.$message.error('代偿金额百分比格式不是数字')
        return false
      }

      const keys = Object.keys(enumValidator)
      for (const key of keys) {
        if (!this.editData[key]) {
          this.$message.error(enumValidator[key])
          return false
        }
      }
      return true
    },
    submit() {
      if (!this.queryId) {
        return
      }
      if (!this.validator()) {
        return
      }
      const data = {
        customer_related_id: this.queryId,
        entrust_entity_name: this.related.customer_name,
        entrust_entity_cert_no: this.isCompany
          ? this.related.register_no
          : this.related.lender_idcard,
        entrust_entity_address: this.editData.entrust_entity_address,
        entrust_entity_phone: this.related.corp_phone,
        bank_name: this.related.claim_bank_name,
        loan_contract_no: this.editData.loan_contract_no,
        loan_contract_name: this.editData.loan_contract_name,
        reply_funds_capital: this.warrantyAmountCapital,
        reply_funds: this.related.warranty_amount * 10000,
        join_no: this.editData.join_no,
        falsify_funds_rate: this.editData.falsify_funds_rate,
        sign_date: this.$utils.dateFormat(new Date(), 'yyyy年MM月dd日'),
        sign_status: 1,
        is_online_sign: 1,
      }
      if (this.hasContract) {
        this.putData(data)
      } else {
        this.postData(data)
      }
    },
    async putData(data) {
      this.submitLoading = true
      const [res] = await this.$utils.promise(
        this.$api.updateData(
          this.$serviceName,
          'entrust_contract',
          this.contract.entrust_contract_id,
          data
        )
      )
      this.submitLoading = false
      if (res) {
        this.$message.success('修改委托合同成功')
        this.$emit('success', 0)
        this.getContract()
        this.beforeClose()
      } else {
        this.$message.error('修改委托合同失败')
      }
    },
    async postData(data) {
      this.submitLoading = true
      const [res] = await this.$utils.promise(
        this.$api.addData(this.$serviceName, 'entrust_contract', data)
      )
      this.submitLoading = false
      if (res) {
        this.getContract()
        this.$message.success('提交委托合同成功')
        this.$emit('success', 1)
        this.beforeClose()
      } else {
        this.$message.error('提交委托合同失败')
      }
    },
    getData() {
      this.related = {}
      if (!this.queryId) {
        return
      }
      this.loading = true
      this.$api
        .getData(this.$serviceName, 'datum_one_county_industry', {
          'customer_related_id.eq': this.queryId,
        })
        .then(res => {
          this.related = res?.data?.[0] ?? {}
        })
        .finally(() => {
          this.loading = false
        })
    },
    getContract() {
      this.editData = {}
      if (!this.queryId) {
        return
      }
      this.$api
        .getData(this.$serviceName, 'entrust_contract', { 'customer_related_id.eq': this.queryId })
        .then(res => {
          this.contract = res?.data?.[0] ?? {}
          this.editData = { ...this.contract }
        })
    },
    beforeClose() {
      this.$emit('update:visible', false)
    },
  },
}
</script>
<style lang="scss" scoped>
.table-vertical-middle td {
  vertical-align: middle;
}
.td-label {
  background-color: #f8f9fa;
  text-align: center;
}
.input-td {
  background-color: #ffffee;
}
</style>
